import { defineStore } from 'pinia';
import router from '@/router/router';
import type { UserInfo } from '@/api/login';

// eslint-disable-next-line no-use-before-define
export type UserStore = ReturnType<typeof useUserStore>;

/**
 * 注册user相关的store
 */
export const useUserStore = defineStore('user', {
  state: () => ({
    /** 用户的 token */
    access_token: undefined as string | undefined,
    /** 设置业务 token */
    refresh_token: undefined as string | undefined,
    /** 用户信息 */
    userInfo: undefined as UserInfo | undefined,
    /** 角色菜单 */
    roleMenu: [] as string[],
  }),
  getters: {
    /** 登录状态 */
    loginStatus: (state) => Boolean(state.access_token && state.refresh_token && state.userInfo),
  },
  actions: {
    /** 设置业务 token */
    setAccessToken(str: string) {
      this.access_token = str;
    },
    /** 设置刷新 token */
    setRefreshToken(str: string) {
      this.refresh_token = str;
    },
    /** 设置用户信息 */
    setUserInfo(data: UserInfo) {
      this.userInfo = data;
    },
    /** 设置角色菜单 */
    setRoleMenu(roleMenu: string[]) {
      this.roleMenu = roleMenu || [];
    },

    /**
     * 退出登录并跳转到登录页面
     * @param isRedirect - 再次登录后是否重定向到本页
     */
    async logout(isRedirect: boolean) {
      await useTabsStore().delAllTabs(true);
      this.access_token = undefined;
      this.refresh_token = undefined;
      this.userInfo = undefined;
      this.roleMenu = [];
      const path = router.currentRoute.value.path;
      if (path !== '/login') {
        const redirect = isRedirect ? `?redirect=${encodeURIComponent(router.currentRoute.value.fullPath || router.currentRoute.value.path)}` : '';
        router.push(`/login${redirect}`);
      }
    },
  },

  /** 持久化储存 依赖 pinia-plugin-persistedstate 插件 */
  persist: {
    key: 'my_pinia_user',
    storage: window.sessionStorage,
  },
});
